<?php


namespace app\controller\admin;


use app\common\model\CommonSearchData;
use app\common\service\redis\PoolRedis;
use app\model\AdminClassroom;
use app\util\ExcelHandle;
use app\util\ReturnCode;
use think\facade\Queue;
use think\facade\Request;
use think\Response;

class Classroom extends Base
{
    public function index() : Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_name = $this->request->get('school_name', '');
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $building_id = $this->request->get('building_id', -1);
        $keywords = $this->request->get('name', '');
        $sortKey = $this->request->get('sortKey', 'create_time');
        $order = $this->request->get('order', 'DESC');

        $where = [
            'AdminClassroom.is_delete' => 0
        ];

        $obj = (new AdminClassroom())->alias('AdminClassroom');

        if ($keywords) {
            $obj = $obj->whereLike('name', "%{$keywords}%");
        }
        if ($school_id > 0) {
            $where['AdminClassroom.school_id'] = $school_id;
        }
        if ($school_name) {
            $obj = $obj->hasWhere('school', function ($query) use ($school_name) {
                $query->where('name', 'like', '%' . $school_name . '%');
            });
        }
        if ($building_id != -1) {
            $where['AdminClassroom.building_id'] = $building_id;
        }

        $listObj = $obj->where($where)->with(['building','school'])
            ->order('AdminClassroom.'.$sortKey, $order)
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total'],
            'buildingList' => CommonSearchData::getTeachingBuilding(AdminClassroom::class, $school_id)
        ]);
    }

    public function add(): Response {
        $school_id = Request::post('school_id/d');
        $building_id = Request::post('building_id/d');
        $name = Request::post('name/s', '', 'strip_tags');
        $bluetooth = Request::post('bluetooth_mac/s', '', 'strip_tags');

        $exists = AdminClassroom::where([
            'is_delete' => 0,
            'bluetooth_mac' => $bluetooth
        ])->find();
        if ($exists) {
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '蓝牙MAC已经存在');
        }
        $classroom = new AdminClassroom();
        $classroom->name = $name;
        $classroom->school_id = $school_id;
        $classroom->building_id = $building_id;
        $classroom->bluetooth_mac = $bluetooth;
        if (!$classroom->save()) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }

    public function edit(): Response {
        $classroom = (new AdminClassroom())->where([
            'is_delete' => 0,
            'id' => $this->request->post('id')
        ])->find();
        if (!$classroom) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '教学楼未找到');
        }

        $school_id = Request::post('school_id/d');
        $building_id = Request::post('building_id/d');
        $name = Request::post('name/s', '', 'strip_tags');
        $bluetooth = Request::post('bluetooth_mac/s', '', 'strip_tags');

        $exists = AdminClassroom::where([
            'is_delete' => 0,
            'bluetooth_mac' => $bluetooth
        ])->where('bluetooth_mac', '<>', $classroom->bluetooth)->find();
        if ($exists) {
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '蓝牙MAC已经存在');
        }

        $classroom->name = $name;
        $classroom->school_id = $school_id;
        $classroom->building_id = $building_id;
        $classroom->bluetooth_mac = $bluetooth;
        if (!$classroom->save()) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        return $this->buildSuccess();
    }

    public function del(): Response {
        $where['is_delete'] = 0;
        $classroom = (new AdminClassroom())->where([
            'is_delete' => 0,
            'id' => $this->request->get('id')
        ])->find();
        if (!$classroom) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '教室未找到');
        }
        $classroom->is_delete = 1;
        $classroom->save();
        return $this->buildSuccess();
    }

    /**
     * @func import
     * @desc 导入职工信息
     * @return \think\Response
     */
    public function upload(): Response  {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('excel_file');
        $school_id = request()->post('school_id');
        // 上传到本地服务器
        try {
            validate(['image'=>'fileSize:20480|fileExt:xls,xlsx'])
                ->check([$file]);
            $fileExtendName = substr(strrchr($file->getOriginalName(), '.'), 1);
            $filePath = $file->getPathname();
            if (is_file($filePath)){
                $cols = [['1' => 'number'],['2' =>'building_name'],['3' => 'name'],['4' => 'bluetooth_mac']];
                $data = ExcelHandle::importExcel($filePath,$cols,$fileExtendName);

                $redis = PoolRedis::instance();
                $redis->multi(\Redis::PIPELINE);
                foreach ($data as $datum) {
                    $datum['school_id'] = $school_id;
                    $redis->lPush("upload_classroom", serialize($datum));
                }
                $redis->exec();
                Queue::push('app\task\job\UploadSyncHandlerJob@fire', [
                    'model'=> AdminClassroom::class,
                    'action' => 'upload_classroom'
                ]);
            }
            return $this->buildSuccess();
        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }

    /**
     * @func download
     * @desc 导出文件
     * @return \think\Response
     */
    public function download(): Response  {
        $titles = [['id' => '序号'],['school_name' => '学校名称'],['building_name'=>'教学楼名称'],['name'=>'教室'],['bluetooth_mac'=>'蓝牙MAC'],['create_time' => '创建时间']];

        $school_name = $this->request->get('school_name', '');
        $school_id = $this->request->get('school_id', 0);
        $building_id = $this->request->get('building_id', -1);
        $keywords = $this->request->get('name', '');

        try {
            $where = [
                'AdminClassroom.is_delete' => 0
            ];

            $obj = (new AdminClassroom())->alias('AdminClassroom');

            if ($keywords) {
                $obj = $obj->whereLike('AdminClassroom.name', "%{$keywords}%");
            }
            if ($school_id > 0) {
                $where['AdminClassroom.school_id'] = $school_id;
            }
            if ($school_name) {
                $obj = $obj->hasWhere('school', function ($query) use ($school_name) {
                    $query->where('name', 'like', '%' . $school_name . '%');
                });
            }
            if ($building_id != -1) {
                $where['AdminClassroom.building_id'] = $building_id;
            }

            $listObj = $obj->where($where)->with(['school','building'])
                ->order('AdminClassroom.create_time', 'DESC')
                ->select()->toArray();
            $exportData = [];
            $len = 1;
            foreach ($listObj as $datum) {
                $datum['name'] .= "\t";
                $datum['bluetooth_mac'] .= "\t";
                $newItem = array_merge(['id' => $len],$datum);
                array_push($exportData, $newItem);
                $len++;
            }
            ExcelHandle::downLoadExcel('教室信息' . date('YmdHi'), $titles, $exportData);

        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }
}